<template>
  <el-dialog title="制作轮播节目" width="90%" style="width: 600px;"  v-model="isVisible" @close="onCancelModel" :close-on-click-modal="false" destroy-on-close append-to-body>
    <div class="yy-template-file">
      <div class="yy-template-file_title">资源选择</div>
      <el-divider class="yy-template-file_divider"/>
      <div class="yy-template-file_item" v-for="form in originForms" :key="form.value">
        <div class="yy-template-file_item-file">
          {{form.fileName}}
        </div>
        <div class="yy-template-file_item-interval" style="margin: 0 10px;">
          <el-input-number v-model="form.interval" :min="5"   style="width: 120px;"/>
        </div>
        <div class="yy-template-file_item-action">
          <span class="yy-template-file_item-action--del" @click="onRemoveOriginItem(form.id)"><el-icon ><Remove /></el-icon></span>
        </div>
      </div>
      <div v-if="isVisible" class="yy-template-file_item" v-for="form in forms" :key="form.id">
        <div class="yy-template-file_item-file">
          <el-tree-select
              v-model="form.fileViewId"
              lazy
              filterable
              :load="load"
              :props="props"
              style="flex:1;"
          >
            <template #default="{ data: { label, isLeaf } }">
              <span>
                <el-icon v-if="!isLeaf"><Folder /></el-icon>
                <el-icon v-else><Document /></el-icon>
              </span>
              <span>{{ label }}</span>
            </template>
          </el-tree-select>
        </div>
        <div class="yy-template-file_item-interval" style="margin: 0 10px;">
          <el-input-number v-model="form.interval" :min="5"   style="width: 120px;"/>
        </div>
        <div class="yy-template-file_item-action">
          <span v-if="forms.length > 1" class="yy-template-file_item-action--del" @click="onRemoveItem(form.id)"><el-icon ><Remove /></el-icon></span>
          <span class="yy-template-file_item-action--add" @click="onAddSelectItem(form.id)"><el-icon ><CirclePlus /></el-icon></span>
        </div>
      </div>
    </div>

    <div class="yy-template-file_setting">
      <div class="yy-template-file_title">播控设置</div>
      <el-divider class="yy-template-file_divider"/>
      <div class="yy-template-file_setting-item">
        <label><span style="color:red;">*</span>节目名称:</label>
        <span style="flex: 1; min-width: 0;"><el-input v-model="settings.name" style="min-width: 120px;"/></span>
      </div>
      <div class="yy-template-file_setting-item">
        <label>发布设备:</label>
        <span style="flex: 1; min-width: 0;">
           <el-select v-model="settings.deviceCodes" placeholder="请选择要发布的设备" clearable multiple style="min-width: 200px;">
            <el-option v-for="option in devices" :label="option.name + `(${option.code})`" :value="option.code" :key="option.code"/>
          </el-select>
        </span>
      </div>
      <div class="yy-template-file_setting-item" v-if="false">
        <label>播放时间:</label>
        <span style="flex: 1; min-width: 0;">
          <span>
             <el-date-picker
                 v-model="settings.startTime"
                 type="datetime"
                 placeholder="开始日期"
                 format="YYYY-MM-DD HH:mm"
                 date-format="YYYY-MM-DD"
                 time-format="HH:mm"
             />
          </span>
          <span> - </span>
          <span>
             <el-date-picker
                 v-model="settings.endTime"
                 type="datetime"
                 placeholder="结束日期"
                 format="YYYY-MM-DD HH:mm"
                 date-format="YYYY-MM-DD"
                 time-format="HH:mm"
             />
          </span>
        </span>
      </div>
      <div class="yy-template-file_setting-item" style="align-items: baseline;">
        <label>播放间隔:</label>
        <div>
          <el-input-number v-model="settings.interval"  :min="1"  style="width: 120px;"/><span> 秒</span>
          <div style="color: #a0a1a7;">该设置只对非视频内容有效，视频默认必须播放完成后才会自动切换下一屏。</div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="onCancelModel">取消</el-button>
        <el-button type="primary" @click="onSaveProgram">{{settings.deviceCodes?.length ? '一键发布' : '保存节目'}}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {defineExpose, defineEmits, nextTick, onBeforeMount, reactive, ref} from "vue";
import {useRouter} from "vue-router";
import ResourceApi from "@/api/broadcast/resource";
import DeviceApi from "@/api/queue/DeviceApi";
import TemplateApi from "@/api/broadcast/template";
import {BcTemplateModel} from "@/model/BcTemplateModel";
import {ElMessage} from "element-plus";

const $emit = defineEmits({
  addSuccess: (data) => data
})
const router = useRouter()
const isVisible = ref(false)
let originData = null
let currentDeptId = null

const props = {
  label: 'label',
  children: 'children',
  isLeaf: 'isLeaf',
}

const forms = ref([
  {
    id: '1',
    fileViewId: '',
    interval: null
  }
])

const settings = ref({
  interval: 5,
  name: '',
  startTime: '',
  endTime: '',
  deviceCodes: []
})
const originForms = ref([])
const devices = ref([])

const load = (node, resolve) => {
  if (node.isLeaf) return resolve([])
  ResourceApi.listFile(node ? node.data.fileId : null, currentDeptId,null, 1, 10000).then((res) => {
    const files = res.rows? res.rows.map(item => ({
      label: item.fileName,
      value: item.viewKey + "__" + item.fileName,
      fileId: item.resId,
      disabled: +item.resCategory === 1,
      isLeaf: +item.resCategory === 2,
      children: +item.resCategory === 2 ? undefined : []
    })) : []
    resolve(files)
  })
}

const listDevice = () => {
  DeviceApi.listDevice(null, null, null, 1, 999).then((res) => {
    devices.value = res.data
  })
}

const onAddSelectItem = (id: string) => {
  const index = forms.value.findIndex(item => item.id === id)
  if (index >= 0) {
    if (index < forms.value.length - 1) {
      forms.value.splice(index + 1, 0, {
        id: getRowId(),
        fileViewId: '',
        interval: null
      })
    } else {
      forms.value.push({
        id: getRowId(),
        fileViewId: '',
        interval: null
      })
    }
  }
}

const onRemoveItem = (id: string) => {
  const index = forms.value.findIndex(item => item.id === id)
  if (index >= 0) {
    forms.value.splice(index, 1)
  }
}

const onRemoveOriginItem = (id: string) => {
  const index = originForms.value.findIndex(item => item.id === id)
  if (index >= 0) {
    originForms.value.splice(index, 1)
  }
}

const onShowDialog = (deptId: string, data: BcTemplateModel) => {
  currentDeptId = deptId
  isVisible.value = true
  listDevice()
  if (data) {
    originData = data
    const config = data.config ? JSON.parse(data.config) : {}
    settings.value = Object.assign({
      name: data.name,
      interval: config.interval,
      startTime: config.startTime,
      endTime: config.endTime,
      deviceCodes: config.deviceCodes
    })
    originForms.value = config.files
  }
}

const getRowId = () => {
  return new Date().getTime() + '_' + Math.random()
}

const onCancelModel = () => {
  isVisible.value = false
  originData = null
  forms.value = [
    {
      id: '1',
      fileViewId: '',
      interval: null
    }
  ]
  settings.value = {
    interval: 5,
    name: '',
    startTime: '',
    endTime: '',
    deviceCodes: []
  }
  originForms.value = []
  devices.value = []
}

const onSaveProgram = () => {
  if(!settings.value.name) {
    ElMessage.warning("请输入节目名称")
    return
  }
  const originDataArr = originData?.id ? originForms.value : []
  const newDataArr = forms.value
      .filter(item => !!item.fileViewId)
      .map(item => {
        const vieIdAndFileName = item.fileViewId.split('__')
        return {
          fileViewId: vieIdAndFileName[0],
          fileName: vieIdAndFileName[1],
          interval: item.interval
        }
      })

  const data = Object.assign({}, settings.value, {
    deptId: currentDeptId,
    type: 'duration',
    id: originData?.id || undefined,
    files: originDataArr.concat(newDataArr)
  })

  TemplateApi.saveTemplateByFile(data).then((res) => {
    $emit('addSuccess', res)
    onCancelModel()
  })
}

defineExpose({
  onShowDialog
})
</script>
<style scoped lang="scss">
.yy-template-file {
  width: 100%;
  height: 100%;
  border: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  &_title {
    width: 100%;
    font-size: 18px;
  }
  &_divider {
    margin-top: 5px;
  }
  &_item {
    display: flex;
    flex-direction: row;
    margin-bottom: 15px;
    width: 100%;
    & > div {
      display: inline-flex;
      align-items: center;
    }
    & > &-file {
      flex: 1;
      min-width: 100px;
    }
    &-action {
      cursor: pointer;
      font-size: 24px;
      width: 100px;
      &--del {
        color: #e81123;
      }
      &--add {
        margin-left: 8px;
        color: #009688;
      }
    }
  }
  &_add {
    width: 100%;
    text-align: center;
  }
  &_setting {
    margin-top: 30px;
    &-item {
      display: inline-flex;
      width: 100%;
      align-items: center;
      margin: 10px 0;
      & > label {
        margin-right: 8px;
      }
    }
  }
}


</style>
<style>
.el-select-dropdown__item {
  padding-right: 12px !important;
}
</style>